from django import forms

from App.bootstrap import BootStrapModelForm
from App.models import User
from App.utils.my_tools import judge_username, judge_password


# 登录表单，继承BootStrapModelForm类
class RegisterForm(BootStrapModelForm):
    username = forms.CharField(
        min_length=3,
        max_length=20,
        label='用户名',
        widget=forms.TextInput(attrs={
            'placeholder': '3-20位，以字母、数字或下划线开头',
        }),
    )
    password = forms.CharField(
        min_length=8,
        label='密码',
        widget=forms.PasswordInput(attrs={
            'placeholder': '最少8位，包含字母数字和符号'
        }),
    )
    ensure_password = forms.CharField(
        min_length=8,
        label='确认密码',
        widget=forms.PasswordInput(attrs={
            'placeholder': '请确认密码'
        }),
    )
    # Root密码
    root_password = forms.CharField(
        min_length=6,
        max_length=6,
        required=False,
        label='Super权限',
        widget=forms.PasswordInput(attrs={
            'placeholder': '请输入Root密码'
        }),
    )

    class Meta:
        model = User  # 必须为数据库中的某个class
        fields = ['username', 'password']  # 获取数据库字段

    # 对用户名进行错误判定
    def clean_username(self):
        username = self.cleaned_data.get('username')
        user = User.objects.filter(username=username)
        if user:
            raise forms.ValidationError('用户名已存在')
        if judge_username(username):
            return username
        else:
            raise forms.ValidationError('用户名不合法')

    # 对密码进行错误判定
    def clean_password(self):
        password = self.cleaned_data.get('password')
        if judge_password(password):
            return password
        else:
            raise forms.ValidationError('密码格式错误，应由字母、数字和符号组成')

    # 对确认密码进行错误判定
    def clean_ensure_password(self):
        password = self.cleaned_data.get('password')
        ensure_password = self.cleaned_data.get('ensure_password')
        if ensure_password == password:
            return ensure_password
        else:
            raise forms.ValidationError('两次密码输入不一致')

    # 对权限进行判定
    def clean_root_password(self):
        root_password = self.cleaned_data.get('root_password')
        super_user = self.data.get('super-user')
        if super_user == 'on' and root_password != '123456':
            raise forms.ValidationError('权限密码错误')

    # 目前字段少不需要这个函数，请保留
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
